package database

import (
	"fmt"
	"time"

	"github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"

	"agentdesign/config"
)

// InitializeMySQL initializes a connection to the MySQL database.
func InitializeMySQL(config *config.DatabaseConfig) (*sqlx.DB, error) {
	// Configure MySQL connection
	mysqlConfig := mysql.Config{
		User:                 config.User,
		Passwd:               config.Password,
		Addr:                 fmt.Sprintf("%s:%d", config.Host, config.Port),
		DBName:               config.Database,
		Net:                  "tcp",
		ParseTime:            true,
		Loc:                  time.UTC,
		AllowNativePasswords: true,
	}

	if mysqlConfig.Params == nil {
		mysqlConfig.Params = make(map[string]string)
	}
	mysqlConfig.Params["multiStatements"] = "true"

	dsn := mysqlConfig.FormatDSN()
	db, err := sqlx.Connect("mysql", dsn)

	if err != nil {
		return nil, fmt.Errorf("%w", err)
	}

	return db, nil
}
